#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <UMCommon/UMCommon.h>
//#import <AppTrackingTransparency/AppTrackingTransparency.h>
//#import <AdSupport/AdSupport.h>
#import <BUAdSDK/BUAdSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"NamingApp";
  self.initialProps = @{};
  [super application:application didFinishLaunchingWithOptions:launchOptions];
  
  [self handleAdData];
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      [self requestIDFATracking];
  });

  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  
//  [self requestIDFA];
  [UMConfigure initWithAppkey:@"64d4529bbd4b621232ecbabc" channel:@"App Store"];
  
  
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(applicationWillResignActive:)
                                               name:UIApplicationWillResignActiveNotification object:nil];
      
      // 监听应用变得活跃的通知
      [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(applicationDidBecomeActive:)
                                               name:UIApplicationDidBecomeActiveNotification object:nil];
      
      // 初始化方法执行状态
      self.shouldPerformActionWhenActive = NO;
      // 设置定时器
      self.timer = [NSTimer scheduledTimerWithTimeInterval:5*60
                                                    target:self
                                                  selector:@selector(timerFired:)
                                                  userInfo:nil
                                                   repeats:YES];
  return YES;
}

- (void)timerFired:(NSTimer *)timer {
  NSLog(@"11112222applicationDidBecomeActive");

    // 定时器触发时的操作
    // 根据需要在此处实现操作
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        [self performPeriodicAction];
    } else {
        // 设置标志，确保当应用下次变为活跃时执行方法
        self.shouldPerformActionWhenActive = YES;
    }
}

- (void)applicationWillResignActive:(NSNotification *)notification {
    // 应用将停止活跃时的操作
    // 比如，无效定时器
    // [self.timer invalidate];
}

- (void)applicationDidBecomeActive:(NSNotification *)notification {
    // 应用已经变成活跃状态
  NSLog(@"11112222applicationDidBecomeActive");

    if (self.shouldPerformActionWhenActive) {
        [self performPeriodicAction];
        self.shouldPerformActionWhenActive = NO;
    }
}

- (void)performPeriodicAction {
    // 执行你想每5分钟运行的操作
  [self.vc loadInterstitialAd];
//    NSLog(@"Performing periodic action!");
  NSLog(@"11112222performPeriodicAction");

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // 应用进入后台
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
  NSLog(@"11112222applicationWillEnterForeground");
    // 应用即将进入前台
    self.shouldPerformActionWhenActive = YES;
}

- (void)dealloc {
    // 移除通知监听者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void) handleAdData{
  NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
  NSDictionary *adData = [userDefault objectForKey:@"adData"];

//  NSString *videoAdIntervalTime = [adData objectForKey:@"videoAdIntervalTime"];
  
  BOOL isShowGDTAd = [[adData objectForKey:@"isShowGDTAd"] boolValue];
  NSString *GDTAppId = [adData objectForKey:@"gDTAppId"];
  if(!GDTAppId){
         GDTAppId = @"1105344611";
  }
  NSLog(@"unifiedInterstitialFailToLoadAd66677%@",GDTAppId);
  [GDTSDKConfig registerAppId:GDTAppId];
  
  BOOL isShowCSJAd = [[adData objectForKey:@"isShowCSJAd"] boolValue];

  NSString *CSJAppId = [adData objectForKey:@"cSJAppId"];
  if(!CSJAppId){
      CSJAppId = @"5446504";
  }
  [self setupBUAdSDK:CSJAppId];
  
  
}

- (void)setupBUAdSDK:CSJAppId {

  BUAdSDKConfiguration *configuration = [BUAdSDKConfiguration configuration];
//      configuration.territory = BUAdSDKTerritory_CN;
      configuration.appID = CSJAppId;//除appid外，其他参数配置按照项目实际需求配置即可。
  configuration.useMediation = YES;

      [BUAdSDKManager startWithAsyncCompletionHandler:^(BOOL success, NSError *error) {
          if (success) {
              dispatch_async(dispatch_get_main_queue(), ^{
           //请求广告逻辑处理
//                ViewController *vc = (ViewController *)self.window.rootViewController;
//                [vc loadGDTVideoAd];
              });
          }
      }];
    
    
//    [self playerCoustomAudio];
    
}

- (void)requestIDFATracking {
    if (@available(iOS 14, *)) {
        // iOS14及以上版本需要先请求权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 获取到权限后，依然使用老方法获取idfa
          NSLog(@"1233212请在设置-隐私-跟踪中允许App请求跟踪123123");
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                    NSLog(@"%@",idfa);
            } else {
                NSLog(@"请在设置-隐私-跟踪中允许App请求跟踪");
            }
        }];
    } else {
        // iOS14以下版本依然使用老方法
        // 判断在设置-隐私里用户是否打开了广告跟踪
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            NSLog(@"%@",idfa);
        } else {
            NSLog(@"请在设置-隐私-广告中打开广告跟踪功能");
        }
    }
}





//- (void)requestIDFA {
//  if (@available(iOS 14, *)) {
//          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//              [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
//                  //其他逻辑代码
//                [self loadAd];
//              }];
//          });
//
//      }
//}
- (UIViewController *)createRootViewController{
  self.vc = [ViewController new];
  [self.vc viewDidLoad];
  return self.vc;
}


- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

/// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
///
/// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
/// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
/// @return: `true` if the `concurrentRoot` feature is enabled. Otherwise, it returns `false`.
- (BOOL)concurrentRootEnabled
{
  return true;
}


@end
